<?php

// +----------------------------------------------------------------------
// | 行为日志控制器
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\im\admin;

use app\event\im\Chat as ChatEvent;
use app\model\im\ChatQuick as ChatQuickModel;
use app\model\im\Robot as RobotModel;
use app\model\im\UserTag;
use app\model\ucenter\User as UserModel;
use app\model\im\Chat as ChatModel;
use app\model\ucenter\Tag as TagModel;

class Worker extends Common
{


    public function index(): string
    {
        $this->assign('static', $this->request->domain());
        return $this->fetch();
    }

    /**
     * 获取会话内容
     * @return \think\response
     */
    public function listing()
    {
        $data['code'] = 0;
        $data['data']['chat_get_time'] = time_format();
        $data['data']['all_unread_count'] = $this->user->chats()
            ->where('status', 1)
            ->where('is_open', 1)
            ->sum('no_read_count');
        $data['data']['services'] = $this->user->chats()->with(['to_user'])
            ->where('status', 1)
            ->where('is_open', 1)
            ->where('queue', 0)
            ->order('last_message_time DESC')
            ->select();
        $data['data']['wait'] = $this->user->chats()
            ->with('to_user')
            ->where('status', 1)
            ->where('to_user_is_online', 1)
            ->where('is_open', 1)
            ->where('queue', '>', 0)
            ->order('last_message_time DESC')->select();
        $data['data']['all_wait_count'] = count($data['data']['wait']);

        return $this->json($data);
    }

    /**
     * 发送短连接消息
     * @return mixed
     */
    public function send()
    {
        // 发送消息
        $event = new ChatEvent();
        $result = $event->send($this->request->param(), $this->user);
        if ($result['code'] == 0) {
            ChatEvent::sendShortConnection($result['data']['content']['id']);
            $result['data'] = $result['data']['content'];
        }
        return $this->json($result);
    }

    /**
     * 领取咨询
     * @return mixed
     */
    public function receive()
    {
        // 发送消息
        $event = new ChatEvent();
        $result = $event->receive($this->request->param(), $this->user);
        return $this->json($result);
    }

    /**
     * 会话内容
     * @return \think\response
     */
    public function conversation()
    {

        $data['code'] = 0;
        $chat = ChatModel::where('store_id',$this->store['id'])->where('id', $this->request->param('chat_id'))->find();
        if ($chat) {
            if ($this->request->param('chat_content_id')) {
                $data['data'] = $chat->contents()->with(['user'])
                    ->order('id DESC')
                    ->where('status', 1)
                    ->where('id', '<', $this->request->param('chat_content_id'))
                    ->paginate(10);
            } else {
                $data['data'] = $chat->contents()->with('user')
                    ->order('id DESC')
                    ->where('status', 1)
                    ->paginate(10);
            }

        } else {
            $data['data'] = [];
            $data['code'] = 1;
        }

        return $this->json($data);
    }

    /**
     * 全部消息消息
     * @return string
     */
    public function history(): string
    {
        $this->assign('chat_id', $this->request->param('chat_id'));
        return $this->fetch();
    }

    /**
     * 转接其他客服
     */
    public function switch()
    {
        if ($this->request->isPost()) {
            $event = new ChatEvent();
            $result = $event->switch($this->request->param(), $this->user);
            return $this->json($result);
        } else {
            $service = UserModel::where('type', '<>', 99)
                ->where('store_id', $this->user['store_id'])
                ->where('status', 1)
                ->where('id', '<>', $this->user['id'])
                ->select();
            $this->assign('service', $service);
            $this->assign('customer_id', $this->request->param('customer_id'));
            $this->assign('name', 123);
            return $this->fetch();
        }
    }

    public function read()
    {
        $data['code'] = 0;
        return $this->json($data);
    }


    public function info()
    {
        $chat = $this->user->chats()->with(['to_user', 'ip_info'])->where('id', $this->request->param('chat_id'))->find();
        $data['data']['customer'] = UserModel::with('tags')->where('id', $chat['to_user_id'])->find();
        $data['data']['chat'] = $chat;
        $data['code'] = 0;
        return $this->json($data);
    }

    public function top()
    {
        if ($this->request->isPost()) {
            $this->user->chats()->where('id', $this->request->param('chat_id'))->update(['is_top' => $this->request->param('is_top')]);
            $data['message'] = '无权限';
            $data['code'] = 1;
            return $this->json($data);
        } else {

            $data['code'] = 0;
            return $this->json($data);
        }
    }

    public function tag()
    {
        if ($this->request->isPost()) {
            $userTags = UserModel::with('tags')->where('id', $this->request->param('customer_id'))->where('store_id', $this->store['id'])->find();;
            if ($userTags) {
                $tags = $this->request->param('tags_id');
                $userTags->tags()->detach();
                $userTags->tags()->attach($tags);
                $data['message'] = '更新成功';
                $data['code'] = 0;
            } else {
                $data['message'] = '无权限';
                $data['code'] = 1;
            }
            return $this->json($data);
        } else {
            $userTags = UserModel::with('tags')->where('id', $this->request->param('customer_id'))->where('store_id', $this->store['id'])->find();;

            $tas = TagModel::where('store_id', $this->store['id'])->where('status', 1)->select();
            $this->assign('userTags', $userTags ? $userTags['tags']->column('id') : []);
            $this->assign('tags', $tas);
            $data['code'] = 0;
            $data['html'] = $this->fetch();
            return $this->json($data);
        }

    }

    /*
     * 更新客户信息
     */
    public function setInfo()
    {

        $update['auth_name'] = $this->request->param('auth_name');
        $update['mobile'] = $this->request->param('mobile');
        $update['introduction'] = $this->request->param('introduction');
        $data['data'] = UserModel::where('id', $this->request->param('customer_id'))->where('store_id',$this->store['id'])->update($update);
        $data['code'] = 0;
        return $this->json($data);
    }


    /**
     * 访客状态
     * @return \think\response
     */
    public function status()
    {

        $data['code'] = 0;
        $data['data'] = UserModel::where('id', $this->request->param('customer_id'))->find();
        return $this->json($data);
    }


    public function quickReply()
    {

        $data['code'] = 0;
        $data['data'] = [];
        return $this->json($data);
    }

//		public function new()
//		{
//			$data['data']['wait_list'] = [];
//			$data['data']['chat_list'] = [];
//			if ($this->request->param('to_user_id')) {
//				$chat = $this->user->chats()->where('to_user_id', $this->request->param('to_user_id'))->find();
//				$data['data']['chat'] = $chat->contents()->with('user')
//					->order('id DESC')
//					->where('status', 1)
//					->where('id', '>', $this->request->param('now_chat_content_id'))
////					->where('id', '>', 10)
//					->order('id ASC')
//					->find();
//				$data['code'] = 0;
//			} else {
//				$data['code'] = 1;
//				$data['message'] = 1;
//			}
//
//			return $this->json($data);
//		}

    /**
     * 关闭客服
     * @return \think\response
     */
    public function close()
    {

        $event = new ChatEvent();
        $result = $event->close($this->request->param(), $this->user);
        $data['code'] = 0;
        $data['data'] = [];
        return $this->json($data);
    }

    /**
     * 黑名单
     * @return \think\response
     */
    public function black()
    {
        if ($this->request->isPost())
        {
            $data['data'] = UserModel::where('type', 99)
                ->where('id', $this->request->param('customer_id'))
                ->where('store_id',$this->store['id'])
                ->update(['status' => $this->request->param('status')]);
            $data['code'] = 0;
            return $this->json($data);
        }else{

            $data['code'] = 0;
            $data['data'] = UserModel::where('status', -1)
                ->where('type', 99)
                ->where('store_id',$this->store['id'])
                ->paginate();
            return $this->json($data);
        }
    }

    /**
     * 快速回复
     * @return \think\response
     */
    public function quick()
    {
        if ($this->request->isPost())
        {
            if ($this->request->param('id'))
            {

            }else{
                // 新增
                $insert = [];
                $insert['title'] = $this->request->param('title');
                $insert['content'] = $this->request->param('content');
                $insert['user_id'] = $this->user['id'];
                $insert['store_id'] = $this->user['store_id'];
                $re  = ChatQuickModel::create($insert);
                $data['code'] = 0;
                $data['data'] = $re;
                $data['message'] = '添加成功';
                return $this->json($data);
            }
            $data['data'] = UserModel::where('status', 1)
                ->where('type', 99)
                ->where('id', $this->request->param('customer_id'))
                ->update(['status' => -1]);
            $data['code'] = 0;
            return $this->json($data);
        }else{

            $data['code'] = 0;
            $data['data'] = ChatQuickModel::where('user_id',$this->user['id'])->select();
            return $this->json($data);
        }
    }

}
